import React, { PureComponent } from 'react';
import PropTypes from 'prop-types';
import { Form } from 'antd';
import _ from 'lodash';

class FormWrap extends PureComponent {

    static propTypes = {
        form: PropTypes.object,
        data: PropTypes.object,
        onComponentDidMount: PropTypes.func,
        renderItems: PropTypes.func,
        handleValidate: PropTypes.func
    }

    doValidate = (callback) => {
        const { form } = this.props;
        const { validateFields } = form;
        validateFields(async (err, values) => {
            callback(err, values);
        });
    }

    componentDidMount() {
        const { form, data, onComponentDidMount=()=>{} } = this.props;
        onComponentDidMount(this.props);
        if (!_.isEmpty(data)) {
            form.setFieldsValue(data);
        }
    }
    render() {
        const { renderItems, form, handleValidate, ...restProps } = this.props;
        if (typeof handleValidate === 'function') {
            this.doValidate(handleValidate);
        }
        const { getFieldDecorator } = form;
        return (
            <Form layout={'vertical'} {...restProps}>
                { renderItems({form, getFieldDecorator}) }
            </Form>
        );
    }

}

export default Form.create({
    onValuesChange(props, values) {
        const { onValuesChange=()=>{} } = props;
        onValuesChange(props, values);
    },
    onFieldsChange(props, fields) {
        const { onFieldsChange=()=>{} } = props;
        onFieldsChange(props, fields);
    }
})(FormWrap);